//
// Created by 123 on 2024/12/27.
//
#include <stdio.h>

typedef struct {
    int id;
    char name[20];
    float salary;
} Employee;

int main078(){
    FILE* fp;
    Employee e1 = {1,"tom",1000};
    Employee e2 = {2,"jeryy",2000};
    Employee e3 = {3,"jack",3000};
    Employee emp;
    int i;

    //写入
    fp = fopen("emplist.bin","wb");
    if(fp == NULL){
        perror("open error");
        return 1;
    }
    fwrite(&e1, sizeof(Employee),1,fp);
    fwrite(&e2, sizeof(Employee),1,fp);
    fwrite(&e3, sizeof(Employee),1,fp);
    //关闭文件
    fclose(fp);

    //读取二进制文件
    fp = fopen("emplist.bin","rb");
    if(fp == NULL){
        perror("open error");
        return 1;
    }
    //获取文件大小
    //移动文件指针到末尾
    fseek(fp,0,SEEK_END);
    //获取当前文件指针二进制位置，因为是末位，末位位置就是文件大小
    long fileSize = ftell(fp);
    //计算元素数量
    int empNumbers = fileSize/sizeof(Employee);
    //重置文件指针到开头
    rewind(fp);

    printf("total employee members:%d\n",empNumbers);

    //访问第三个元素信息,索引位置为2
    int targetIndex = 2;
    if(targetIndex<empNumbers){
        //移动指针,距离文件开头2个元素的偏移量
        fseek(fp,targetIndex* sizeof(Employee),SEEK_SET);
        //然后阅读一个元素，并给emp
        fread(&emp, sizeof(Employee),1,fp);
        printf("index:%d\n",targetIndex+1);
        printf("id:%d\n",emp.id);
        printf("name:%s\n",emp.name);
        printf("salary:%.2f\n",emp.salary);
    }else{
        printf("over range !");
    }
    fclose(fp);



    return 0;
}